<?php

namespace App\Jobs;

use App\Models\LoanApplication;
use App\Models\LoanCreditProvident;
use App\Models\LoanGeneral;
use App\Models\LoanMortgageCar;
use App\Models\LoanMortgageHouse;
use App\Models\LoanMortgageTax;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Rap2hpoutre\FastExcel\Facades\FastExcel;

class ImportLoan implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 600;

    protected  $filepath = '';

    protected  $category = '';

    protected  $uid = '';
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($filepath, $category, $uid)
    {
        $this->filepath = $filepath;
        $this->category = $category;
        $this->uid = $uid;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $category = $this->category;
        $user = User::find($this->uid);

        if(empty($user)) return;

        if ($category == 'credit-provident') {
            $header = array_flip(LoanCreditProvident::TEMPLATE_HEADER);
        } elseif ($category == 'mortgage-car') {
            $header = array_flip(LoanMortgageCar::TEMPLATE_HEADER);
        } elseif ($category == 'mortgage-house') {
            $header = array_flip(LoanMortgageHouse::TEMPLATE_HEADER);
        }  elseif ($category == 'mortgage-tax') {
            $header = array_flip(LoanMortgageTax::TEMPLATE_HEADER);
        }  elseif ($category == 'general') {
            $header = array_flip(LoanGeneral::TEMPLATE_HEADER);
        } else {
            return;
        }

        $org_root = $user->org_root;
        $processCacheKey = md5($this->filepath);

        $data = FastExcel::import(Storage::path($this->filepath));
        $stat = ['total' => $data->count(), 'success'=> 0, 'fail' => 0, 'duplicate' => 0, 'progress'=> 0];
        Cache::put($processCacheKey,  $stat, 1800);

        foreach ($data as $v) {
            $row = [];
            foreach ($header as $k => $h) {
                $row[$h] = isset($v[$k]) ? trim($v[$k]) : '';
            }

            $mobile = $row['mobile'];
            if (LoanApplication::where('mobile', $mobile)->exists()) {
                 $stat['duplicate']++;
            } else {
                try {
                    $this->saveRow($user, $row,  $category);
                    $stat['success']++;
                } catch (\Exception $e) {
                    Log::warning('import job cant save to db: ' . $e->getMessage(), $e->getTrace());
                    $stat['fail']++;
                }
            }

            $stat['progress']++;

            // 10 条数据更新一次进度
            if ($stat['progress'] % 10 == 0) {
                Cache::put($processCacheKey,  $stat, 1800);
            }
        }

        Cache::put($processCacheKey,  $stat, 600);
        Storage::delete($this->filepath);
    }

    /**
     * 保存到数据库
     *
     * @param $row
     * @param $user
     * @param $category
     * @return void
     */
    protected function saveRow($user, $row, $category) {
        list($amount_start, $amount_end) =  parseAmount($row['amount']);

        $loan = new LoanApplication();
        $loan->org_root = $user->org_root;
        $loan->org_code = $user->org_code;
        $loan->source = 1;

        $time = !empty($row['apply_at']) ? strtotime( $row['apply_at']) : false;
        $loan->apply_at = $time ? date("Y-m-d H:i:s", $time) : date("Y-m-d H:i:s");
        $loan->mobile = $row['mobile'];
        $loan->name = $row['name'];
        $loan->amount_start = $amount_start;
        $loan->amount_end = $amount_end;
        $loan->need_home_service = (int) ($row['need_home_service'] == "是");

        // 兼容只填写地址栏
        $addr = $row['addr'];
        $addrArr = explode(" ", $addr);
        $loan->province = empty($row['province']) ? ($addrArr[0] ?? '') : '';
        $loan->city = empty($row['city']) ? ($addrArr[1] ?? '') : '';
        $loan->district = empty($row['district']) ? ($addrArr[2] ?? '') : '';
        $loan->addr = count($addrArr) == 1 ? $row['addr'] : ($addrArr[3] ?? '');

        $loan->category = $category;
        $loan->save();

        if ($category == 'credit-provident') {
            $loan->creditProvident()->create([
                "company_name" => $row['company_name'] ?? '',
                "pay_method" => $row['pay_method'] ?? '',
                "month_salary" => (int) $row['month_salary'] ?? 0,
                "provident_age" => (int) $row['provident_age'] ?? 0,
                "month_provident" => (int) $row['month_provident'] ?? 0,
                "social_insurance_age" => (int) $row['social_insurance_age'] ?? 0,
                "month_social_insurance" => (int) $row['month_social_insurance'] ?? 0,
            ]);
        } elseif ($category == 'mortgage-car') {
            $loan->mortgageCar()->create([
                "info" => $row['info'] ?? '',
                "car_age" => (int) $row['car_age'] ?? 0,
                "buy_price" => (int) $row['buy_price'] ?? 0,
                "car_model" => $row['car_model'] ?? '',
                "car_no" => $row['car_no'] ?? '',
            ]);
        } elseif ($category == 'mortgage-house') {
            $loan->mortgageHouse()->create([
                'type' => $row['type'] ?? '',
                'has_certificate' => (bool) $row['has_certificate'] ?? 0,
                'ownership' => $row['ownership'] ?? '',
                'latest_estimated' => (int) $row['latest_estimated'] ?? 0,
            ]);
        } elseif( $category=='mortgage-tax') {
            $loan->mortgageTax()->create([
                "company_name" => $row['company_name'] ?? '',
                "annal_tax" => (int) $row['annal_tax'] ?? 0,
                "annal_turnover" =>(int)  $row['annal_turnover'] ?? 0,
                "company_age" => (int) $row['company_age'] ?? 0,
                "is_legal_person" => (bool) $row['is_legal_person'] ?? 0,
            ]);
        } elseif ( $category=='general') {
            $loan->custom_field = $row['custom_field'] ?? '';
            $loan->save();
        }
    }

    /**
     * Handle a job failure.
     *
     * @param  \Throwable  $exception
     * @return void
     */
    public function failed(\Throwable $exception)
    {
        Log::warning("import job failed " . $exception->getMessage() , $exception->getTrace());
    }
}
